<?php
namespace Home\Controller;
use Think\Controller;
use Home\Biz\CommonBiz;
use Home\Biz\Alipay;
use Home\Biz\OrderBiz;
use Home\Biz\StringBiz;
use Home\Biz\PromoterBiz;
use Home\Biz\AdminBiz;

class IndexController extends BaseController {
    public function index(){
    	//验证当前用户是否登陆
    	$login_user_id = cookie(C('AdminConfig.login_cookie_name'));

    	if(empty($login_user_id)){
    		//未登录
    		redirect(C('UrlConfig.login_url'));
    		return;
    	}else{
    	    redirect(C('UrlConfig.home_url'));
    		return;
    	}
    }
    
    public function employeelogin() {
    	$this->assign('page_name', 'o2o云推广员工登陆');
    	$this->display ( "index/employeelogin" );
    }
    
    public function login() {
    	$this->assign('page_name', '登陆');
    	$this->display ( "index/login" );
    }
    
    public function register() {
    	$this->assign('page_name', '注册');
    	$share_code = I('share_code');
    	$this->assign('share_code', $share_code);
    	$this->display ( "index/register" );
    }
    
    
    /**
     * 注册提交form的action处理
     * 注册用户，图片上传
     */
    public function registerAction() {
    	/*** 参数校验 start ***/
    	$promoter_id= PromoterBiz::generatePromoterId();
    	$promoter_en = array(
    			'promoter_id'	=> $promoter_id,
    			'promoter_type'	=> I('promoter_type'),
    			'sex'			=> I('sex'),
    			'promoter_name' => I('real_name'),
    			'real_name'		=> I('real_name'),
    			'password'		=> I('password'),
    			'alipay_id'		=> I('alipay_id'),
    			'alipay_name'	=> I('alipay_name'),
    			'cellphone'		=> I('cellphone'),
    			'district_id'	=> I('district_id'),
    			'address'		=> I('address'),
    			'id_card_no'	=> I('id_card_no'),
    			'register_ip'	=> get_client_ip(),
    			'register_date' => date("y-m-d H:i:s", time()),
    			'status'		=> 0,
    			'create_user'	=> 'whaleyFZ IndexController registerAction',
    			'create_date'	=> date("y-m-d H:i:s", time()),
    	);
    	
    	$recommend_share_code = I('share_code');
    	/*** 参数校验 end ***/
    	
    	
    	/*** 图片上传 start ***/
    	$upload_config = array(
    			'maxSize'	=> 0,
    			'rootPath'	=> './Public/Uploads/',
    			'savePath'	=> 'promoter/'.$promoter_id.'/',
    			'saveName'  => array('uniqid',''),
    			'exts'		=> array('jpg', 'gif', 'png', 'jpeg'),
    			'subName' => '',
    			'replace' => true,
    	);

    	$upload = new \Think\Upload($upload_config); // 实例化上传类
        $upload->autoSub = false;

    	$info = $upload->upload();
    	$upload_image_array = array();
    	if (!$info) { 
			// 转到注册失败页面
			redirect(C('UrlConfig.common_error_url').'?type=11&param=缺少证件照片上传(图片过大，不要超过2mb)，'.$upload->getError());
    		return;
		}
    	else{
    		foreach($info as $file){
    			$key = $file['key'];
    			$upload_image_array['path'] = $file['savepath'].$file['savename'];
    			switch($key){
    				case 'file_id_card1':
    					if(empty($promoter_en['id_card_image_list'])){
    						$promoter_en['id_card_image_list'] = $file['savepath'].$file['savename'];
    					}
    					else{
    						$promoter_en['id_card_image_list'] = $promoter_en['id_card_image_list'].'|'.$file['savepath'].$file['savename'];
    					}
    					break;
    				case 'file_id_card2':
    					if(empty($promoter_en['id_card_image_list'])){
    						$promoter_en['id_card_image_list'] = $file['savepath'].$file['savename'];
    					}
    					else{
    						$promoter_en['id_card_image_list'] = $promoter_en['id_card_image_list'].'|'.$file['savepath'].$file['savename'];
    					}
    					break;
    				case 'file_business_license':
    					$promoter_en['business_license_image'] = $file['savepath'].$file['savename'];
    					break;
    				case 'file_organization':
    					$promoter_en['organization_image'] = $file['savepath'].$file['savename'];
    					break;
    				case 'file_tax_registration':
    					$promoter_en['tax_registration_image'] = $file['savepath'].$file['savename'];
    					break;
    				default:
    					break;
    			}
    		}
    			
    	}
    	/*** 图片上传 end ***/
    	
    	
    	$error_msg = AdminBiz::register($promoter_en, $recommend_share_code);
    	echo $error_msg;
    	if(!empty($error_msg)){
    		redirect(C('UrlConfig.common_error_url').'?type=12&param='.$error_msg);
    		return;
    	}
    	else{
			redirect(C('UrlConfig.common_info_url').'?type=11');
    		return;
    	}
    }
    
 
    
    /**
     * 找回密码
     */
    public function findPwd(){
    	$this->assign('page_name', '找回密码');
    
    	$this->display("promoter/findPwd");
    }
    
    
    public function noticelist(){
    	$this->assign('page_name', '公告列表');
    	
    	$this->display("index/noticelist");
    }
    
    
    public function noticedetail(){
    	$this->assign('page_name', '公告详情');
    	 
    	$this->display("index/noticedetail");
    }


    /**
     * 售后与政策页面
     */
    public function policy(){
        $this->assign('page_name', '售后与政策');

        $this->display("index/policy");
    }

	/**
	 * 注册隐私条款
	 */
	public function privacy(){
		$this->assign('page_name', '隐私条款');

        $this->display("index/privacy");
	}
    
    /**
     * 错误信息显示页面
     */
    public function commonError(){
    	// 参数获取begin
    	$type = I ( 'type' );
    	if (empty ( $type )) {
    		$type = 0;
    	}
    	
    	$param = I('param');
    	// 参数获取end
    
    	$msg = '';
    	switch ($type) {
    		case 11:
    			$msg = "注册失败，请联系客服。";
    			break;
    		case 12:
    			$msg = "注册失败，请联系客服。";
    			break;
    		case 21:
    			$msg = "不存在推荐码，无法购买。";
    			break;
    		case 22:
    			$msg = "不存在购买的商品。";
    			break;
    		case 22:
    			$msg = "不存在推荐人。";
    			break;
    		case 31:
    			$msg = "不存在的订单编号，无法支付。";
    			break;
    		case 32:
    			$msg = "订单不存在。";
    			break;
    		case 33:
    			$msg = "支付宝请求失败。";
    			break;
    		case 34:
    			$msg = "订单".$param."已经支付过了。";
    			break;
    		default :
    			$msg = "抱歉，发生错误，请重试。";
    			break;
    	}
    
    	$this->assign('msg', $msg);
    	$this->assign('param', $param);
    	$this->display ( "index/common_error" );
    }
    
    
    /**
     * 错误信息显示页面
     */
    public function commonInfo(){
    	// 参数获取begin
    	$type = I ( 'type' );
    	if (empty ( $type )) {
    		$type = 0;
    	}
    	 
    	$param = I('param');
    	// 参数获取end
    
    	$msg = '';
    	switch ($type) {
    		case 11:
    			$msg = "注册成功，请等待客服审核。";
    			break;
    	}
    
    	$this->assign('msg', $msg);
    	$this->display ( "index/common_info" );
    }
    
    
    
    public function auditError() {
    	// 参数获取begin
    	$promoter_id = I ( 'promoter_id' );
    	$type = I ( 'type' );
    	if (empty ( $type )) {
    		$type = 1;
    	}
    	// 参数获取end
    
    	$msg = '';
    	switch ($type) {
    		case 1 :
    			$msg = "抱歉，当前用户不存在。";
    			break;
    		case 2 :
    			$msg = "抱歉，当前用户尚在审核中。";
    			break;
    		case 3 :
    			$msg = "抱歉，当前用户审核已被拒绝。";
    			$promoterStatusChangeLog_en = M('promoterStatusChangeLog')->where("promoter_id='%s' AND status=2", $promoter_id)->order('`create_date` DESC')->find();
    			$msg = $msg."<br/>(".$promoterStatusChangeLog_en['remark'].")";
    			break;
    		case 4 :
    			$msg = "抱歉,当前用户信息还未同步到数据库。";
    			break;
    		case 21:
    			$msg = "错误，当前用户与查看用户不符。";
    			break;
    		case 22:
    			$msg = "错误，用户安全码错误，请重新登陆。";
    			break;
    		default :
    			$msg = "抱歉，用户发生错误，请重试。";
    			break;
    	}
    
    	$this->assign('type', $type);
    	$this->assign('msg', $msg);
    	$this->display ( "index/audit_error" );
    }
    
    
    public function testAlipay(){
    	$order_id = 'SO10039888';
    	 
    	$order_en = M('orderInfo', '', 'DB_trade')->where("order_id='$order_id'")->find();
    	$lst_order_detail_en = M('orderDetail', '', 'DB_trade')->where("order_id='$order_id'")->select();
    	$all_goods_qty = 0;
    	foreach($lst_order_detail_en as $order_detail_en){
    		$all_goods_qty = $all_goods_qty + $order_detail_en['qty'];
    	}
    	 
    	 
    	$alipay_config = array();
    	//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    	//合作身份者ID，签约账号，以2088开头由16位纯数字组成的字符串，查看地址：https://b.alipay.com/order/pidAndKey.htm
    	$alipay_config['partner']		= '2088911659298453';
    	//收款支付宝账号，以2088开头由16位纯数字组成的字符串，一般情况下收款账号就是签约账号
    	$alipay_config['seller_id']	= $alipay_config['partner'];
    	// MD5密钥，安全检验码，由数字和字母组成的32位字符串，查看地址：https://b.alipay.com/order/pidAndKey.htm
    	$alipay_config['key']			= 'clvbnhz4merg9v6fkvelob4762frhlg2';
    	// 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    	$alipay_config['notify_url'] = '';
    	// 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    	$alipay_config['return_url'] = '';
    	//签名方式
    	$alipay_config['sign_type']    = strtoupper('MD5');
    	//字符编码格式 目前支持utf-8
    	$alipay_config['input_charset']= strtolower('utf-8');
    	//ca证书路径地址，用于curl中ssl校验
    	//请保证cacert.pem文件在当前文件夹目录中
    	$alipay_config['cacert']    = './Public/alipay/cacert.pem';
    	//访问模式,根据自己的服务器是否支持ssl访问，若支持请选择https；若不支持请选择http
    	$alipay_config['transport']    = 'http';
    	// 支付类型 ，无需修改
    	$alipay_config['payment_type'] = "1";
    	// 产品类型，无需修改
    	$alipay_config['service'] = "alipay.wap.create.direct.pay.by.user";
    	//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
    
    	 
    	//商户订单号
    	$out_trade_no = $order_en['order_id'];
    	//订单名称
    	$subject = '订单编号：'.$order_en['order_id'];
    	//付款金额
    	$total_fee = $order_en['order_amount'];
    	//订单描述
    	$body = '订单编号：'.$order_en['order_id'];
    	//商品展示地址
    	$show_url = 'http://o.whaley.cn/buy/cart';
    	 
    	 
    	 
    	//构造要请求的参数数组，无需改动
    	$parameter = array(
    			"service"       => $alipay_config['service'],
    			"partner"       => $alipay_config['partner'],
    			"seller_id"  => $alipay_config['seller_id'],
    			"payment_type"	=> $alipay_config['payment_type'],
    			"notify_url"	=> $alipay_config['notify_url'],
    			"return_url"	=> $alipay_config['return_url'],
    			"_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
    			"out_trade_no"	=> $out_trade_no,
    			"subject"	=> $subject,
    			"total_fee"	=> $total_fee,
    			"show_url"	=> $show_url,
    			"body"	=> $body,
    	);
    	 
    	//建立请求
    	vendor('alipay.alipay_submit');
    	$alipaySubmit = new \AlipaySubmit($alipay_config);
    	//     	echo json_encode($parameter);return;
    	$html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
    	//echo json_encode($html_text);return;
    	echo $html_text;
    	 
    }
    
    public function test(){
        $lst_sku_str = 'SK10422945,2|SK10422943,1';
    	$result = OrderBiz::calcCart($lst_sku_str);


        echo json_encode($result);
    }
    /**
     * Description: 缓存TOKEN方法
     * @version 2016年8月31日 上午10:38:09 
     * @author lin.yujiao@whaley.cn
     * @return mixed
     */
    private function accessToken() {
    	$tokenFile = "./access_token.txt";//缓存文件名
    	$data = json_decode(file_get_contents($tokenFile));
    	if ($data->expire_time < time() or !$data->expire_time) {
    		$corpid = C('WeChatConfig.corpid');
    		$secret = C('WeChatConfig.secret');
    		$token_url  = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corpid&corpsecret=$secret";
   			$token_result = json_decode(file_get_contents($token_url), true);
    		$access_token = $token_result['access_token'];
    		if($access_token) {
    			$data->expire_time = time() + 7000;
    			$data->access_token = $access_token;
    			$fp = fopen($tokenFile, "w");
    			fwrite($fp, json_encode($data));
    			fclose($fp);
    			/* $data['expire_time'] = time() + 7000;
    			$data['access_token'] = $access_token;
    			$fp = fopen($tokenFile, "w");
    			fwrite($fp, json_encode($data));
    			fclose($fp); */
    		}
    	} else {
    		$access_token = $data->access_token;
    	}
    	return $access_token;
    }
    
    /**
     * Description: 企业号获取登录信息及通讯录信息
     * @version 2016年8月30日 下午2:33:24 
     * @author lin.yujiao@whaley.cn
     */
    public function testForWeixin(){
    	//通过GET请求获取从微信认证的CODE并发起请求获取企业accessToken
    	$code = $_GET["code"];
    	$access_token = $this->accessToken();
    	if(!empty($code) && !empty($access_token)){
    		//通过CODE与TOKEN获取当前登录的企业用户ID
    		$user_url  = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=$access_token&code=$code";
    		$user_result = json_decode(file_get_contents($user_url), true);
    		$open_id = $user_result['UserId'];
    		if(!empty($open_id)){
    			//通过用户ID访问通讯录获取详细通讯录内的详细信息
    			$company_user_url  = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=$access_token&userid=$open_id";
		   		$company_user_result = json_decode(file_get_contents($company_user_url), true);
		   		if(!empty($company_user_result) && !empty($company_user_result['userid']) && !empty($company_user_result['name'])){
		   			$user_id	= $company_user_result['userid'];
		   			$user_name	= $company_user_result['name'];
		   			$create_user	= 'whaleyFZ AjaxService adminService.employeeLogin';
		   			//利用详细信息在O2O平台中进行快捷登录若操作成功跳转至首页
		   			if(AdminBiz::employeeSimpleLogin($user_id, $user_name, $create_user)){
		   				redirect(C('UrlConfig.home_url'));
		   				return;
		   			}
		   		}
    		}
    	}
    	/* echo "<br/>code:".$code;
    	echo "<br/>access_token:".$access_token;
    	echo "<br/>user_result:".json_encode($user_result);
    	echo "<br/>open_id:".$open_id;
    	echo "<br/>company_user_url:".json_encode($company_user_url);
    	echo "<br/>user_id:".$company_user_result['userid'];
    	echo "<br/>user_name:".$company_user_result['name']; */
    	redirect(C('UrlConfig.audit_error_url').'?type=4');
    	return;
   	}
   	
    /**
     * Description: 个人微信登录信息获取
     * @version 2016年8月31日 上午9:53:39 
     * @author lin.yujiao@whaley.cn
     */
    public function testPersonWeixin(){
    	$refresh_flag = false;
    	$appid = 'wx22637ce143759407';
    	$secret = '94bda3999ba3092e2fe9765cd7f8b77a';
    	$code = $_GET["code"];
    	echo "<br/>第一步 获取CODE:";
    	if(empty($code)){
    		echo "获取失败";
    		return;
    	}
    	echo "<br/>";
    	echo json_encode($code);
    	
    	echo "<br/><br/>第二步 根据CODE发起GET请求获取TOKEN信息:";
    	$token_url  = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
    	$token_result = json_decode(file_get_contents($token_url), true);
    	if(empty($token_result)){
    		echo "获取失败";
    		return;
    	}
    	$access_token = $token_result['access_token'];
    	$refresh_token = $token_result['refresh_token'];
    	$openid = $token_result['openid'];
    	echo "<br/>access_token:";
    	echo $access_token;
    	echo "<br/>expires_in:";
    	echo $token_result['expires_in'];
    	echo "<br/>refresh_token:";
    	echo $refresh_token;
    	echo "<br/>openid:";
    	echo $openid;
    	echo "<br/>scope:";
    	echo $token_result['scope'];
    	//若需要刷新token
    	if($refresh_flag){
    		echo "<br/><br/>第三步 根据REFERSH_TOKEN发起GET请求刷新TOKEN信息:";
    		$refresh_url  = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
    		$refresh_result = json_decode(file_get_contents($refresh_url), true);
    		if(empty($refresh_result)){
    			echo "获取失败";
    			return;
    		}
    		$access_token = $refresh_result['access_token'];
    		$refresh_token = $refresh_result['refresh_token'];
    		$openid = $refresh_result['openid'];
    		echo "<br/>access_token:";
    		echo $access_token;
    		echo "<br/>expires_in:";
    		echo $refresh_result['expires_in'];
    		echo "<br/>refresh_token:";
    		echo $refresh_token;
    		echo "<br/>openid:";
    		echo $openid;
    		echo "<br/>scope:";
    		echo $refresh_result['scope'];
    	}
    	
    	//拉取用户信息(需scope为 snsapi_userinfo)
    	echo "<br/><br/>最后 拉取用户信息(需scope为 snsapi_userinfo):";
    	$user_url  = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
    	$user_result = json_decode(file_get_contents($user_url), true);
    	if(empty($user_result)){
    		echo "获取失败";
    		return;
    	}
    	echo "<br/>openid:";
    	echo $user_result['openid'];
    	echo "<br/>nickname:";
    	echo $user_result['nickname'];
    	echo "<br/>province:";
    	echo $user_result['province'];
    	echo "<br/>city:";
    	echo $user_result['city'];
    	echo "<br/>country:";
    	echo $user_result['country'];
    	echo "<br/>headimgurl:";
    	echo $user_result['headimgurl'];
    	echo "<br/>privilege:";
    	echo $user_result['privilege'];
    	echo "<br/>unionid:";
    	echo $user_result['unionid'];
    	//附：检验授权凭证（access_token）是否有效
    	//https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
    	//正确的Json返回结果：{ "errcode":0,"errmsg":"ok"}
    	//错误时的Json返回示例：{ "errcode":40003,"errmsg":"invalid openid"}
    }
    
    public function levelProduct(){
        $this->display ( "index/levelProduct" );
    }


    /**
     * 生成订单购买的二维码图
     */
	public function orderBuyQRCode(){
    	try{
    		$order_id = I('order_id');
    	
    		Vendor('phpqrcode.phpqrcode');
    	
    		$url 	= C('UrlConfig.payment_transfer_QRCode_url').'?order_id='.$order_id; //二维码内容
    	
    		$logo	= 'Public/image/logo.jpg';
    		
    		$qr_file_path = "Public/image/orderPayment/".$order_id.".png";
    		if(!file_exists($qr_file_path)){
    			//不存在订单支付二维码图片时，生成二维码图片
    			\QRcode::png($url, $qr_file_path, $level = QR_ECLEVEL_M, $size = 10, $margin = 3, $saveandprint=false);
			}
    		
    		$QR = $qr_file_path;
			
    			
    		if ($logo !== FALSE) {
    			$QR = imagecreatefromstring(file_get_contents($QR));
    			$logo = imagecreatefromstring(file_get_contents($logo));
    			$QR_width = imagesx($QR);//二维码图片宽度
    			$QR_height = imagesy($QR);//二维码图片高度
    			$logo_width = imagesx($logo);//logo图片宽度
    			$logo_height = imagesy($logo);//logo图片高度
    			$logo_qr_width = $QR_width / 5;
    			$scale = $logo_width/$logo_qr_width;
    			$logo_qr_height = $logo_height/$scale;
    			$from_width = ($QR_width - $logo_qr_width) / 2;
    			//重新组合图片并调整大小
    			imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
    					$logo_qr_height, $logo_width, $logo_height);
    		}
    		//输出图片
    		imagepng($QR, $qr_file_path);
    		
    		$img = file_get_contents($qr_file_path, true);
    		//使用图片头输出浏览器
    		header("Content-Type: image/jpeg;text/html; charset=utf-8");
    		echo $img;
    	}
    	catch(Exception $e){
    		echo json_encode($e);
    	}
    }
    
    
    public function joinQRCode(){
    	try{
	    	$share_code = I('share_code');
	    	
	    	Vendor('phpqrcode.phpqrcode');
	    	
	    	$url 	= C('UrlConfig.join_promoter_QRcode_url').'?share_code='.$share_code; //二维码内容   
	    	
			$logo	= 'Public/image/logo.jpg';
	    	//生成二维码图片
			\QRcode::png($url, "Public/image/qrcode.png", $level = QR_ECLEVEL_M, $size = 10, $margin = 3, $saveandprint=false);
	 		$QR = 'Public/image/qrcode.png';
			
			if ($logo !== FALSE) {
				$QR = imagecreatefromstring(file_get_contents($QR));
				$logo = imagecreatefromstring(file_get_contents($logo));
				$QR_width = imagesx($QR);//二维码图片宽度
				$QR_height = imagesy($QR);//二维码图片高度
				$logo_width = imagesx($logo);//logo图片宽度
				$logo_height = imagesy($logo);//logo图片高度
				$logo_qr_width = $QR_width / 5;
				$scale = $logo_width/$logo_qr_width;
				$logo_qr_height = $logo_height/$scale;
				$from_width = ($QR_width - $logo_qr_width) / 2;
				//重新组合图片并调整大小
				imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
						$logo_qr_height, $logo_width, $logo_height);
			}
			//输出图片
			imagepng($QR, 'Public/image/helloweixin.png');
			//echo 'http://local.o.whaley.cn/public/image/helloweixin.png';
			$img = file_get_contents('Public/image/helloweixin.png',true);
			//使用图片头输出浏览器
			header("Content-Type: image/jpeg;text/html; charset=utf-8");
			echo $img;
    	}
    	catch(Exception $e){
    		echo json_encode($e);
    	}
    }
    
    
    public function buyQRCode(){
    	 
    	$share_code = I('share_code');
    	 
    	Vendor('phpqrcode.phpqrcode');
    	 
    	$url 	= C('UrlConfig.buy_QRCode_url').'?share_code='.$share_code; //二维码内容
    	 
    	$logo	= 'Public/image/logo.jpg';
    	//生成二维码图片
    	\QRcode::png($url, "Public/image/qrcode.png", $level = QR_ECLEVEL_M, $size = 10, $margin = 3, $saveandprint=false);
    	$QR = 'Public/image/qrcode.png';
    
    
    	if ($logo !== FALSE) {
    		$QR = imagecreatefromstring(file_get_contents($QR));
    		$logo = imagecreatefromstring(file_get_contents($logo));
    		$QR_width = imagesx($QR);//二维码图片宽度
    		$QR_height = imagesy($QR);//二维码图片高度
    		$logo_width = imagesx($logo);//logo图片宽度
    		$logo_height = imagesy($logo);//logo图片高度
    		$logo_qr_width = $QR_width / 5;
    		$scale = $logo_width/$logo_qr_width;
    		$logo_qr_height = $logo_height/$scale;
    		$from_width = ($QR_width - $logo_qr_width) / 2;
    		//重新组合图片并调整大小
    		imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
    				$logo_qr_height, $logo_width, $logo_height);
    	}
    	//输出图片
    	imagepng($QR, 'Public/image/helloweixin.png');
    	//echo 'http://local.o.whaley.cn/public/image/helloweixin.png';
    	$img = file_get_contents('Public/image/helloweixin.png',true);
    	//使用图片头输出浏览器
    	header("Content-Type: image/jpeg;text/html; charset=utf-8");
    	echo $img;
    
    }
    
    
    public function testQRCode(){
    	$this->display('test/testQRCode');
    }

    
    public function test1(){
    
    }
    
    
    /**
     * 分成 Start
     */
    public function revenueAll(){
    	header("Content-Type: text/html; charset=UTF-8");
    	$order_id = I('order_id');
    	
    	if(empty($order_id)){
	    	$lst_revenue_promoter_order = M('promoterOrder')
	    	->where("order_revenue_status = 0 AND order_status = 35 AND payment_status = 1")
	    	->select();
    	}
    	else{
    		$lst_revenue_promoter_order = M('promoterOrder')
    		->where("order_id='$order_id' AND order_revenue_status = 0 AND order_status = 35 AND payment_status = 1")
    		->select();
    	}
    	echo '订单数量'.count($lst_revenue_promoter_order);
    	
    	
    	$lst_sku_en = M('sku', '', 'DB_trade')->where("is_buy_fz=1")->select();
    	foreach($lst_revenue_promoter_order as $promoter_order_en){
    		
    		
    		$promoter_id 	 	= $promoter_order_en['promoter_id'];
    		$lst_promoter_order_detail	= M('promoter_order_detail')->where("order_id='%s'", array($promoter_order_en['order_id']))->select();
    		
    		$order_revenue_amount = 0;
    		foreach($lst_promoter_order_detail as $promoter_order_detail_en){
    			$qty			            = $promoter_order_detail_en['qty'];

    			$revenue_amount = $this->revenueToPseron($promoter_id,
    					$promoter_order_en,
                        $promoter_order_detail_en,
    					$qty);
    			
    			$order_revenue_amount = $order_revenue_amount + $revenue_amount;
    		}
    		
    		
    		//更新用户promoterInfo的余额
    		$promoterInfo_en 		= M('promoterInfo')->where("promoter_id='%s'", array($promoter_id))->find();
    		$promoterInfo_amount	= $promoterInfo_en['amount'];
    		$new_promoterInfo_amount= $promoterInfo_amount + $order_revenue_amount;
    		M('promoterInfo')->where("promoter_id='%s'", array($promoter_id))->setField('amount', $new_promoterInfo_amount);
    		
    	
    		//写入用户余额变更
    		$add_promoter_amount_en = array(
    				'promoter_id'		=>	$promoter_order_en['promoter_id'],
    				'promoter_name'		=>	$promoter_order_en['promoter_name'],
    				'amount_kind'		=>	1,
    				'amount_type'		=>	12,
    				'amount'			=>	$order_revenue_amount,
    				'begin_amount'		=>	$promoterInfo_amount,
    				'end_amount'		=>	$new_promoterInfo_amount,
    				'order_id'			=>	$promoter_order_en['order_id'],
    				'remark'			=>	'订单'.$promoter_order_en['order_id'].'分成'.strval($order_revenue_amount).'元',
    				'withdraw_flag'		=>	0,
    				'status'			=>	1,
    				'create_user'			=> 'whaleyFZ.Job revenueAll',
    				'create_date'			=> date("y-m-d H:i:s", time()),
    		);
    		M('promoterAmount')->add($add_promoter_amount_en);
    		
    		
    		//更新promoterOrder相应状态
    		$update_promoterOrder_en = array(
    				'order_revenue_status'	=> 3,
    				'revenue_amount'		=> $order_revenue_amount
    		);
    		
    		M('promoterOrder')->where("order_id='%s'", array($promoter_order_en['order_id']))->save($update_promoterOrder_en);
    	}
    	
    }
    
    
    
    public function revenueToPseron($promoter_id, $promoter_order_en, $promoter_order_detail_en, $qty){
    	
    	//此订单中商品需分成的金额
    	$revenue_amount = 0;
        $revenue_amount = $promoter_order_detail_en['person_commission_amount'] * $qty;

    	//写入分成明细
    	$add_promoter_order_revenue_detailEn = array(
    			'order_id'			=>	$promoter_order_en['order_id'],
    			'third_order_id'	=>	$promoter_order_en['third_order_id'],
    			'promoter_id'		=>	$promoter_order_en['promoter_id'],
    			'promoter_name'		=>	$promoter_order_en['promoter_name'],
    			'promoter_type'		=>	$promoter_order_en['promoter_type'],
    			'qty'				=>	$qty,
    			'revenue_type'		=>	1,
    			'revenue_amount'	=>  $revenue_amount,
    			'sku_sn'			=>	$promoter_order_detail_en['sku_id'],
    			'sku_name'			=>	$promoter_order_detail_en['sku_name'],
    			'style_sn'			=>	$promoter_order_detail_en['style_id'],
    			'style_name'		=>	$promoter_order_detail_en['style_name'],
    			'person_commission_amount'	=>	$promoter_order_detail_en['person_commission_amount'],
    			'dealer_commission_amount'	=>	$promoter_order_detail_en['dealer_commission_amount'],
    			'status'			=>	1,
    			'create_user'			=> 'whaleyFZ.Job revenueAll',
    			'create_date'			=> date("y-m-d H:i:s", time()),
    	);
    	M('promoterOrderRevenueDetail')->add($add_promoter_order_revenue_detailEn);
    	
		return $revenue_amount;
    }
    
    /**
     * 分成 Start
     */
    
    
    /**
     * 转为可提现 Start
     */
    public function ConvertWithdrawAll(){
    	header("Content-Type: text/html; charset=UTF-8");
    	
    	//1.获取所有需转入的推广人余额
    	$lst_promoterAmount_en = M('promoterAmount')->where(array('withdraw_flag'=>0))->select();

        echo json_encode($lst_promoterAmount_en);
    	//2.将推广人余额写入可提现余额
    	foreach($lst_promoterAmount_en as $promoterAmount_en){
    		switch($promoterAmount_en['amount_type']){
    			case 12:
    				//订单提成，需7日后进入可提现余额
                    $convert_flag   = false;
                    if(empty($promoterAmount_en['order_id'])){
                        $date1 = date_create($promoterAmount_en['create_date']);
                        $date2 = date_create();
                        $diff  = date_diff($date1,$date2);
                        $interval_hours = $diff->days * 24 + $diff->h;
                        if($interval_hours > 7*24){
                            $convert_flag   = true;
                        }
                    }
                    else{
                        $order_id   = $promoterAmount_en['order_id'];
                        $order_date = M('orderInfo', '', 'DB_trade')->where("order_id='%s'", $order_id)->getField('order_date');

                        $date1 = date_create(date("y-m-d H:i:s", $order_date));
                        $date2 = date_create();
                        $diff  = date_diff($date1,$date2);
                        $interval_hours = $diff->days * 24 + $diff->h;
                        if($interval_hours > 12*24){
                            $convert_flag   = true;
                        }
                    }


    				if($convert_flag == true){
    					$this->ConvertWithdrawAmount($promoterAmount_en);
    				}
    				break;
    			default:
    				$this->ConvertWithdrawAmount($promoterAmount_en);
    				break;
    		}
    		
    	}
    	
    	echo 'succ';
    }
    
    
    public function ConvertWithdrawAmount($promoterAmount_en){
    	//1.更改用户可提现余额
    	$promoterInfo_en = M('promoterInfo')->where(array('promoter_id'=>$promoterAmount_en['promoter_id']))->find();
    	if(empty($promoterInfo_en)){
    		return;
    	}
    	
    	$withdraw_amount 		= $promoterAmount_en['amount'];
    	$begin_withdraw_amount 	= $promoterInfo_en['withdraw_amount'];
    	$end_withdraw_amount	= 0;
    	if($promoterAmount_en['amount_kind'] == 1){
    		$end_withdraw_amount	= $begin_withdraw_amount + $withdraw_amount;
    	}
    	else{
    		$end_withdraw_amount	= $begin_withdraw_amount - $withdraw_amount;
    	}
    	
    	
    	M('promoterInfo')->where(array('promoter_id'=>$promoterAmount_en['promoter_id']))->setField('withdraw_amount', $end_withdraw_amount);
    	
    	//2.将数据写入promoter_withdraw_amount
    	$add_promoter_withdraw_amount_en = array(
    			'promoter_id'	=> $promoterAmount_en['promoter_id'],
    			'promoter_name'	=> $promoterAmount_en['promoter_name'],
    			'amount_kind'	=> $promoterAmount_en['amount_kind'],
    			'amount_type'	=> $promoterAmount_en['amount_type'],
    			'withdraw_amount'		=> $withdraw_amount,
    			'begin_withdraw_amount'	=> $begin_withdraw_amount,
    			'end_withdraw_amount'	=> $end_withdraw_amount,
    			'order_id'		=> $promoterAmount_en['order_id'],
    			'remark'		=> $promoterAmount_en['remark'],
    			'status'		=> 1,
    			'create_user'	=> 'job ConvertWithdrawAll',
    			'create_date'	=> date("y-m-d H:i:s", time()),
    	);
    	M('promoterWithdrawAmount')->add($add_promoter_withdraw_amount_en);
    	
    	
    	//3.更改当前数据的状态
    	M('promoterAmount')->where(array('id'=>$promoterAmount_en['id']))->setField('withdraw_flag', 1);
    }
    
    
    public function Add50Amount(){
    	$lst_promoter_order_en = M()->query("
    			SELECT * FROM whaley_fz.`promoter_order`
				WHERE `order_revenue_status` = 3
				AND revenue_amount = 50");
    	
    	foreach($lst_promoter_order_en as $promoter_order_en){
    		$order_id = $promoter_order_en['order_id'];
    		$promoter_id = $promoter_order_en['promoter_id'];
    		
    		
    		//更新用户promoterInfo的余额
    		$promoterInfo_en 		= M('promoterInfo')->where("promoter_id='%s'", array($promoter_id))->find();
    		$promoterInfo_amount	= $promoterInfo_en['amount'];
    		$new_promoterInfo_amount= $promoterInfo_amount + 25;
    		M('promoterInfo')->where("promoter_id='%s'", array($promoter_id))->setField('amount', $new_promoterInfo_amount);
    		
    		
    		//写入用户余额变更
    		$add_promoter_amount_en = array(
    				'promoter_id'		=>	$promoter_order_en['promoter_id'],
    				'promoter_name'		=>	$promoter_order_en['promoter_name'],
    				'amount_kind'		=>	1,
    				'amount_type'		=>	11,
    				'amount'			=>	25,
    				'begin_amount'		=>	$promoterInfo_amount,
    				'end_amount'		=>	$new_promoterInfo_amount,
    				'order_id'			=>	$promoter_order_en['order_id'],
    				'remark'			=>	'订单'.$order_id.'分成补增25元',
    				'withdraw_flag'		=>	0,
    				'status'			=>	1,
    				'create_user'			=> 'whaleyFZ Add50Amount',
    				'create_date'			=> date("y-m-d H:i:s", time()),
    		);
    		M('promoterAmount')->add($add_promoter_amount_en);
    	}
    	
    }
    /**
     * 转为可提现 End
     */
}